package com.cop4331.social;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * 
 * @author Daniel Moody
 * @LastUpdated: 4/12/2012 by Matt Szoke
 * 
 * Allows user to edit their distinct profile
 * 
 */
public class EditProfileActivity extends Activity {

	EditText full;
	EditText email;
	EditText phone;
	EditText pw;
	EditText rpw;
	EditText answer;
	EditText oldpw;
	EditText major;
	TextView err;
	Button register;
	Button cancel;
	Spinner spinner;
	Spinner spinner_question;
	
	// -----------------------------------------------
	// ONCREATE
	// -----------------------------------------------
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		
		// Add xml
		setContentView(R.layout.editprofilelayout);

		// Instantiate Variables

		// EditText
		full = (EditText) findViewById(R.id.ep_fullname);
		email = (EditText) findViewById(R.id.ep_email);
		phone = (EditText) findViewById(R.id.ep_phone);
		major = (EditText) findViewById(R.id.ep_major);
		rpw = (EditText) findViewById(R.id.ep_repass);
		pw = (EditText) findViewById(R.id.ep_password);
		oldpw = (EditText) findViewById(R.id.epeditoldpass);
		answer = (EditText) findViewById(R.id.ep_answer);
		
		// Buttons
		register = (Button) findViewById(R.id.ep_register);
		cancel = (Button) findViewById(R.id.epcancel);
		
		// Spinners
		spinner = (Spinner) findViewById(R.id.ep_gender);
		spinner_question = (Spinner) findViewById(R.id.ep_security);
		
		// TextView for Errors
		err = (TextView) findViewById(R.id.ep_error);
		

		// Get current user info from database
		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		HashMap<String, String> user = db.getUserDetails();
		final String un = user.get("name");
		UserFunctions uf = new UserFunctions();
		JSONObject json = uf.userExists(un);

		// Temp strings used to get info
		String tempPassString = null;
		String tempQuestionString = null;
		String tempAnswerString = null;

		try {
			// Get current user info that is in database
			JSONObject j_user = json.getJSONObject("user");
			full.setText(j_user.getString("full"));
			email.setText(j_user.getString("email"));
			phone.setText(j_user.getString("phone"));
			major.setText(j_user.getString("major"));
			if (j_user.getString("gender").compareTo("Male") == 0) {
				spinner.setSelection(0);
			} else {
				spinner.setSelection(1);
			}
			tempQuestionString = j_user.getString("sec");
			tempAnswerString = j_user.getString("ans");
			tempPassString = j_user.getString("password");

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}

		// Data has been retrieved set the data
		final String CurrentPassword = tempPassString;
		final String CurrentQuestion = tempQuestionString;
		final String CurrentAnswer = tempAnswerString;

		register.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				// Registration Values
				String fullName = full.getText().toString();
				String em = email.getText().toString();
				String phoneNum = phone.getText().toString();
				String oldpass = oldpw.getText().toString();
				String pass = pw.getText().toString();
				String rpass = rpw.getText().toString();
				String gender = spinner.getSelectedItem().toString();
				String question = spinner_question.getSelectedItem().toString();
				String ans = answer.getText().toString();
				String maj = major.getText().toString();

				// No Name
				if (fullName.compareTo("") == 0) {
					err.setText("Please enter your full name.");
				}

				// No Email
				else if (em.compareTo("") == 0) {
					err.setText("Please enter a email.");
				}
				
				else if (em.compareTo("") == 0) {
					err.setText("Please enter an email address.");
				}

				else if ((oldpass.compareTo("") == 0 && (pass.compareTo("") != 0 || rpass
						.compareTo("") != 0))// <<--- old password is empty
												// while others are not
						|| (pass.compareTo("") == 0 && (oldpass.compareTo("") != 0 || rpass
								.compareTo("") != 0))// <<--- pass is empty
														// while others are not
						|| (rpass.compareTo("") == 0 && (oldpass.compareTo("") != 0 || pass
								.compareTo("") != 0)))// <<--- rpass is empty
														// while others are not
				{
					err.setText("Please enter your old and new password.");
				}

				else if ((spinner_question.getSelectedItemPosition() != 0 && ans
						.compareTo("") == 0)// <<---spinner set to dont change
											// while answer is filled
						|| (spinner_question.getSelectedItemPosition() == 0 && ans
								.compareTo("") != 0))// <<---spinner set to
														// change while answer
														// is unfilled
				{
					err.setText("Please enter a security question and answer.");
				}

				else if (oldpass.compareTo("") != 0
						&& oldpass.compareTo(CurrentPassword) != 0)// <<---old
																	// password
																	// is
																	// incorrect
				{
					err.setText("Incorrect password.");
				}

				else if (pass.compareTo(rpass) != 0) // <<-- passwords do not
														// match
				{
					err.setText("New Passwords do not match.");
				}

				else {
					UserFunctions userFunction = new UserFunctions();

					if (oldpass.compareTo("") == 0 && pass.compareTo("") == 0
							&& rpass.compareTo("") == 0)// <<-- case where user
														// does not want to
														// change password
					{
						pass = CurrentPassword;
					}
					if (spinner_question.getSelectedItemPosition() == 0) // <<--case
																			// where
																			// user
																			// does
																			// not
																			// want
																			// to
																			// hange
																			// security
																			// question
					{
						question = CurrentQuestion;
						ans = CurrentAnswer;
					}
					// this sends the update info
					JSONObject json = userFunction.editUserDetails(un,
							fullName, em, phoneNum, pass, gender, question,
							ans, maj);

					try {
						if (json.getString("success") != null) {

							err.setText("");
							String res = json.getString("success");

							if (Integer.parseInt(res) == 0) {
								err.setText("Error, Unable to update");
							} else {

								Intent ImageUpload = new Intent(
										getApplicationContext(),
										ViewProfileActivity.class);
								startActivity(ImageUpload);
								finish();
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		});

		// Cancel button, return to loginactivity
		cancel.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent vp = new Intent(getApplicationContext(),
						ViewProfileActivity.class);
				startActivity(vp);
				finish();

			}
		});
		
		// Buttons for Title Bar
		ImageButton about, home, message;

		about = (ImageButton) findViewById(R.id.b_about);
		home = (ImageButton) findViewById(R.id.b_home);
		message = (ImageButton) findViewById(R.id.b_message);
		
		// Check for new messages
		JSONObject j_mess = uf.retreiveMessages(un, "new");

		try {
			if (Integer.parseInt(j_mess.getString("size")) > 0) {
				message.setVisibility(View.VISIBLE);
			} else
				message.setVisibility(View.GONE);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

		// Show app info
		about.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Dialog dialog = new Dialog(EditProfileActivity.this);

				dialog.setContentView(R.layout.help_dialog);
				dialog.setTitle("CramSessions v 1.0 2012");
				dialog.setCancelable(true);

				// Create and show a dialog to help the user with this specific
				// field
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("CramSessions was created by:\n\n-Matt Szoke\n-Daniel Moody\n-Jeovanny Alvarez\n-Kia Manoochehri\n-Rj Anderson\n-Doug Wagner");
				text.setGravity(Gravity.LEFT);
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		});

		// Button to return home (dashboard)
		home.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						DashBoardActivity.class);
				startActivity(sa);
				finish();

			}
		});
		
		// Button to message inbox, only if new message exists
		message.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						MessageNotifications.class);
				startActivity(sa);
				finish();

			}
		});
	}
}
